package com.ag.oa.core.service.impl;

import com.ag.oa.core.dao.IMessageDao;
import com.ag.oa.core.dao.ITaskDao;
import com.ag.oa.core.entity.vo.TaskVO;
import com.ag.oa.core.entity.vo.UserVO;
import com.ag.oa.core.service.ITaskService;
import com.ag.oa.util.CustomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Author:   wjc
 * Date:     2021/10/25
 * Description:
 */
@Service("taskServiceImpl")
public class TaskServiceImpl implements ITaskService {

    @Autowired
    private ITaskDao taskDao;

    @Autowired
    private IMessageDao messageDao;

    @Override
    public List<TaskVO> getTaskPageList(Integer projectId, Integer page, Integer pageSize) {

        return taskDao.getForPageList(projectId, page * pageSize, pageSize);
    }

    @Override
    public void createTask(TaskVO taskVO) {

        taskDao.createTask(taskVO);
        taskDao.createTaskFirstUser(taskVO);
    }

    @Override
    public List<TaskVO> findTaskList(TaskVO taskVO) {

        return taskDao.findTaskList(taskVO);
    }

    @Override
    public void saveNewTaskForum(Integer userId, Integer taskId, String contentStr) {

        // 保存评论
        taskDao.saveForum(userId, taskId, contentStr);
    }

    @Override
    public void findUserTaskPageList(Integer userId, Integer fromPage, JSONObject res) {

        if (fromPage==0) {
            // 我的任务列表
            JSONObject result = new JSONObject();
            List<Integer> proList = new ArrayList<>();

            List<Map> tempList = taskDao.getUserAllTaskProjectList(userId);
            for (Map map: tempList) {
                int score = Integer.parseInt(map.get("score").toString());

                JSONObject taskObj = new JSONObject();
                taskObj.put("taskId", map.get("taskId"));
                taskObj.put("taskName", map.get("taskName"));
                taskObj.put("score", map.get("score"));

                Integer projectId = Integer.valueOf(map.get("projectId").toString());
                if (proList.indexOf(projectId)==-1) {
                    proList.add(projectId);
                }

                JSONObject temp;
                if (result.containsKey(projectId.toString())) {
                    temp = result.getJSONObject(projectId.toString());
                    JSONArray taskArr = temp.getJSONArray("tasks");
                    taskArr.add(taskObj);
                    temp.put("tasks", taskArr);
                    temp.put("totalScore", temp.getInteger("totalScore") + score);

                } else {
                    temp = new JSONObject();
                    temp.put("projectId", projectId);
                    temp.put("projectName", map.get("projectName"));
                    temp.put("status", map.get("status"));
                    temp.put("totalScore", score);

                    JSONArray taskArr = new JSONArray();
                    taskArr.add(taskObj);
                    temp.put("tasks", taskArr);
                }
                // 结果集
                result.put(projectId.toString(), temp);
            }

            List<Object> projectTaskList = new ArrayList<>();
            for (Integer projectId: proList) {
                projectTaskList.add(result.getJSONObject(projectId.toString()));
            }
            res.put("taskArr", projectTaskList);

        } else if (fromPage==1) {
            List<Map> tasks = taskDao.getUserAllTaskList(userId);  // 填写工作周报内容时获取
            res.put("taskArr", tasks);
        }
    }

//    @Override
//    public List<Map> getUserProjectTaskScoreList(Integer userId) {
//
//        return taskDao.getProjectTaskScoreDataList(userId);
//    }

    @Override
    public TaskVO getTaskById(Integer taskId) {

        return taskDao.getTaskById(taskId);
    }

    @Override
    public TaskVO getTaskUserStatus(Integer taskId, Integer userId) {

        return taskDao.getTaskUserStatus(taskId, userId);
    }

    @Override
    public void updateTaskStatus(TaskVO vo) {

        taskDao.updateTaskStatus(vo);
    }

    @Override
    public void updateTaskDesc(TaskVO vo) {

        taskDao.updateTaskDesc(vo);
    }

    @Override
    public void createTaskUsers(TaskVO vo) {

        // 1. 创建任务与用户的关系
        taskDao.createTaskUsers(vo);

        // 2. 发送系统消息
        String batchId = CustomUtil.getUUID32();
        if (vo.getRecieveType()==0) {
            // 2.1 自己领取任务，系统消息发送给当前任务所有负责人(包括发起人，至少有一条数据)
            List<Integer> toUserIdList = taskDao.getManagerUserIdByTaskId(vo.getTaskId());
            messageDao.saveNewMessage(2, vo.getCreatedBy(), toUserIdList, vo.getTaskId()
                    , null, 0, batchId, null, 0, null);

        } else if(vo.getRecieveType()==1) {
            // 2.2 负责人指派任务，系统消息发送给指派人
            messageDao.saveNewMessage(4, vo.getCreatedBy(), vo.getUserIds(), vo.getTaskId()
                    , null, 0, batchId, null, 0, null);
        }
    }

    @Override
    public void updateCompleteTask(TaskVO vo) {

        // 1. 完成任务
        taskDao.updateCompleteTask(vo);

        // 2. 发送任务完成消息（主动点击完成任务情况）
        String batchId = CustomUtil.getUUID32();
        if (vo.getCompleteType()==0) {
            List<Integer> toUserIdList = taskDao.getManagerUserIdByTaskId(vo.getTaskId());
            messageDao.saveNewMessage(3, vo.getUserId(), toUserIdList, vo.getTaskId()
                    , vo.getCompleteDesc(), 0, batchId, null, 0, null);
        }
    }

    @Override
    public List<TaskVO> findTaskUserById(Integer taskId, Integer completeStatus) {

        return taskDao.findTaskUserById(taskId, completeStatus);
    }

    @Override
    public List<UserVO> getTaskUserCheckDataList(String username, Integer taskId, Integer limitCount) {

        return taskDao.getTaskUserCheckDataList(username, taskId, limitCount);
    }

    @Override
    public void updateUserMixedStatus(TaskVO vo) {

        Integer userMixedStatus = vo.getUserMixedStatus();

        if (userMixedStatus==1 || userMixedStatus==2) {
            // 1. 修改任务的用户职责
            taskDao.updateTaskResp(vo);

        } else if (userMixedStatus==3) {
            // 2. 修改任务的用户完成情况
            vo.setCompleteType(1); // 属于负责人强制完成任务
            taskDao.updateCompleteTask(vo);

            // 2.1 发送收到完成任务消息
            String batchId = CustomUtil.getUUID32();
            List<Integer> toUserIdList = new ArrayList<>();
            toUserIdList.add(vo.getUserId());
            messageDao.saveNewMessage(5, vo.getUpdatedBy(), toUserIdList, vo.getTaskId(), null
                    , 0, batchId, null, 0, null);
        }
    }

    @Override
    public List<TaskVO> getNewRunTaskTop10() {

        // 项目的Map
        Map<Integer,TaskVO> projectMap = new LinkedHashMap<>();
        List<TaskVO> taskVOList = taskDao.getNewRunTaskTop10();
        for (TaskVO vo: taskVOList) {
            if (projectMap.containsKey(vo.getProjectId())) {
                // 如果存在
                List<TaskVO> subTaskArr = projectMap.get(vo.getProjectId()).getSubTaskArr();
                subTaskArr.add(new TaskVO(vo.getTaskId(),vo.getTaskName()));
                vo.setSubTaskArr(subTaskArr);
                projectMap.put(vo.getProjectId(),vo);
            } else {
                List<TaskVO> subTaskArr = new ArrayList<>();
                subTaskArr.add(new TaskVO(vo.getTaskId(),vo.getTaskName()));
                vo.setSubTaskArr(subTaskArr);
                projectMap.put(vo.getProjectId(),vo);
            }
        }
        return new ArrayList<>(projectMap.values());
    }

}
